<script setup>
import { ref, onMounted, nextTick } from 'vue'
import PrimaryButton from '@/components/PrimaryButton.vue'

// 搜索关键词
const searchKey = ref('')
// 搜索框引用
const searchInput = ref(null)

// 搜索历史记录
const searchHistory = ref([])

// 从本地存储加载搜索历史
const loadSearchHistory = () => {
  try {
    const history = uni.getStorageSync('searchHistory')
    if (history) {
      searchHistory.value = JSON.parse(history)
    }
  } catch (e) {
    console.error('加载搜索历史失败', e)
  }
}

// 保存搜索历史到本地存储
const saveSearchHistory = () => {
  try {
    uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value))
  } catch (e) {
    console.error('保存搜索历史失败', e)
  }
}

// 添加搜索历史
const addSearchHistory = () => {
  if (!searchKey.value.trim()) return

  // 如果已存在相同的搜索词，先删除旧的
  const index = searchHistory.value.indexOf(searchKey.value)
  if (index !== -1) {
    searchHistory.value.splice(index, 1)
  }

  // 将新的搜索词添加到最前面
  searchHistory.value.unshift(searchKey.value)

  // 限制历史记录数量，最多保存20条
  if (searchHistory.value.length > 20) {
    searchHistory.value = searchHistory.value.slice(0, 20)
  }

  saveSearchHistory()

  // 执行搜索操作
  search()
}

// 删除单个搜索历史
const deleteHistory = (index) => {
  searchHistory.value.splice(index, 1)
  saveSearchHistory()
}

// 清空所有搜索历史
const clearAllHistory = () => {
  searchHistory.value = []
  saveSearchHistory()
}

// 点击历史记录项执行搜索
const searchByHistory = (keyword) => {
  searchKey.value = keyword
  search()
}

// 执行搜索
const search = () => {
  console.log('搜索关键词:', searchKey.value)
  // 这里可以添加实际的搜索逻辑
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 组件挂载时加载搜索历史并自动聚焦
onMounted(() => {
  loadSearchHistory()
  // 自动聚焦搜索框
  nextTick(() => {
    if (searchInput.value) {
      searchInput.value.focus()
    }
  })
})
</script>

<template>
  <view class="search-page f-col">
    <!-- 搜索 -->
    <view
      class="flex white-bgc"
      style="
          --van-search-background: #F7F8FA;
          --van-swipe-indicator-inactive-opacity: 1;
          --van-swipe-indicator-inactive-background: #1a1617;
        "
    >
      <!-- 返回上一个页面 -->
      <view class="flex-center p-l-20">
        <van-icon
          name="arrow-left"
          size="36rpx"
          @click="goBack"
        />
      </view>
      <!-- 搜索框 -->
      <view class="flex-1">
        <van-search
          v-model="searchKey"
          placeholder="请输入商品名称或者分类"
          shape="round"
          wrap-with-form
          :clearable="false"
          background="white"
          @search="addSearchHistory"
          ref="searchInput"
          autofocus
        />
      </view>
      <view class="p-tb-20 flex-center m-r-20 c-3 fs-24">
        <PrimaryButton
          text="搜索"
          padding-t-b="15rpx"
          padding-l-r="40rpx"
          @click="addSearchHistory"
        />
      </view>
    </view>

    <!-- 搜索历史 -->
    <view
      class="search-history p-15"
      v-if="searchHistory.length > 0"
    >
      <view class="history-header flex-between p-b-10">
        <text class="fs-24 c-3">搜索历史</text>
        <view
          @click="clearAllHistory"
          class="c-6 fs-24 flex-center"
        >
          <text class="delete-icon icon icon-shanchu m-r-5"></text>清空
        </view>
      </view>

      <view class="m-t-10 flex flex-wrap">
        <view
          v-for="(item, index) in searchHistory"
          :key="index"
          class="history-tag br-30 c-6 m-r-15 m-b-15 flex-center relative fs-24"
          @click="searchByHistory(item)"
        >
          <text class="tag-text">{{ item }}</text>
          <view
            class="tag-delete flex-center"
            @click.stop="deleteHistory(index)"
          >
            <van-icon
              name="cross"
              size="12"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 无搜索历史时显示 -->
    <view
      class="f-col-c p-30 flex-1"
      v-else
    >
      <van-empty
        image="search"
        description="暂无搜索历史"
      />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.search-header {
  position: sticky;
  top: 0;
  z-index: 100;
}

.history-tag {
  background-color: #f2f3f5;
  padding: 10rpx 20rpx;
  padding-right: 50rpx;
}

.tag-text {
  max-width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag-delete {
  position: absolute;
  right: 15rpx;
}

.delete-icon {
  height: 36rpx;
  width: 36rpx;
}
</style>